package com.dormitoryAdministratorSystem.ui.classmanage;

import com.dormitoryAdministratorSystem.entity.clazz.ClassBean;
import com.dormitoryAdministratorSystem.service.clazz.impl.ClassSerImpl;
import com.dormitoryAdministratorSystem.ui.MainFrame;
import com.dormitoryAdministratorSystem.util.BeansUtil;
import com.dormitoryAdministratorSystem.util.CheckFormatUtil;
import com.lovo.netCRM.component.LovoButton;
import com.lovo.netCRM.component.LovoDate;
import com.lovo.netCRM.component.LovoTxt;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Date;

public class ClassAddDialog extends JDialog {
	
	private LovoTxt classTxt;
	private LovoTxt teacherTxt;
	private LovoDate classOpenTime;
	private LovoButton addBtn;
	private LovoButton cancelBtn;

	private ClassSerImpl csi = new ClassSerImpl();
	
	public ClassAddDialog(MainFrame frame){
		super(frame, "学生换房", true);
		this.setBounds(550, 300, 300, 280);
		this.setLayout(null);
		this.init();

		this.setVisible(true);
	}

	private void init() {
		// TODO Auto-generated method stub
		this.classTxt = new LovoTxt("班级名称", 20, 20, this);
		this.teacherTxt = new LovoTxt("带班老师", 20, 80, this);
		this.classOpenTime = new LovoDate("开班时间", 20, 140, this);
		this.addBtn = new LovoButton("添加", 40, 200, this);
		this.cancelBtn = new LovoButton("取消", 150, 200, this);

		this.addBtn.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				try {
					if("".equals(classTxt.getText().trim()) || "".equals(teacherTxt.getText().trim())){
						JOptionPane.showMessageDialog(null, "添加失败，信息不能为空");
					}else if(!CheckFormatUtil.checkLength(classTxt.getText().trim(), 2, 20) ||
							!CheckFormatUtil.checkLength(teacherTxt.getText().trim(), 2, 10)){
						JOptionPane.showMessageDialog(null,
								"添加失败\n" +
										"姓名长度范围： 2-10\n" +
										"班级名称长度范围： 2-20");
					}else if(BeansUtil.getcMap().get(classTxt.getText().trim()) != null){
						JOptionPane.showMessageDialog(null, "添加失败，班级名称重复");
					}else{
						ClassBean c = new ClassBean();
						c.setCName(classTxt.getText().trim());
						c.setTeacherName(teacherTxt.getText().trim());
						c.setOpenTime(new Date(classOpenTime.getDate().getTime()));
						if(csi.addClass(c) == 1){
							JOptionPane.showMessageDialog(null,"添加成功");
						}else{
							JOptionPane.showMessageDialog(null,"添加失败");
						}
					}
				}catch (Exception e1){
					JOptionPane.showMessageDialog(null,"日期格式输入错误，添加失败");
				}

				ClassAddDialog.this.dispose();
			}
		});

		this.cancelBtn.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				ClassAddDialog.this.dispose();
			}
		});
	}
	
}
